import axios from 'axios';
import { baseUrl } from './config.js';

// 获取 Authorization Header
function getAuthHeaders() {
  const token = localStorage.getItem('token');
  return {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  };
}

// 登录接口
export function login02(account, password) {
  return axios.post(`${baseUrl}/api/users/loginADMIN`, {
    username: account,
    password: password
  }, {
    headers: {
      'Content-Type': 'application/json'
    }
  });
}

// // 响应拦截器，处理 Token 过期情况
// axios.interceptors.response.use(response => {
//   return response;
// }, error => {
//   if (error.response && error.response.status === 401) {
//     // Token 过期或无效，重定向到登录页面
//     alert("登录已过期，请重新登录");
//     window.location.href = '/';
//   }
//   return Promise.reject(error);
// });

// 获取所有用户
export function fetchAllUsers() {
  return axios.get(`${baseUrl}/api/users/all`, {
    headers: getAuthHeaders()
  });
}

// 搜索用户
export function searchUsers(keyword) {
  return axios.get(`${baseUrl}/api/users/search`, {
    params: { keyword },
    headers: getAuthHeaders()
  });
}

// 更新用户
export function updateUser(userId, userData) {
  return axios.put(`${baseUrl}/api/users/${userId}`, userData, {
    headers: getAuthHeaders()
  });
}

export function addUser(userData) {
  return axios.post(`${baseUrl}/api/users/register`, userData, {
    headers: getAuthHeaders()  // 添加身份验证的请求头
  })
  .then(response => {
    return response.data;  // 返回成功的响应数据
  })
  .catch(error => {
    console.error('Error adding user:', error);
    throw error;  // 抛出错误以供调用者处理
  });
}


// 删除用户
export function deleteUser(userId) {
  return axios.delete(`${baseUrl}/api/users/${userId}`, {
    headers: getAuthHeaders()
  });
}


// 获取所有卡片
export async function fetchCards() {
  try {
    const response = await axios.get(`${baseUrl}/api/cards`, {
      headers: getAuthHeaders(),
    });
    return response.data;
  } catch (error) {
    console.error('获取卡片失败:', error);
    throw error;
  }
}

// 添加新卡片
export async function addCard(cardForm) {
  try {
    const response = await axios.post(`${baseUrl}/api/cards`, cardForm, {
      headers: getAuthHeaders(),
    });
    return response.data;
  } catch (error) {
    console.error('添加卡片失败:', error);
    throw error;
  }
}

// 更新卡片
export async function updateCard(cardId, cardForm) {
  try {
    const response = await axios.put(`${baseUrl}/api/cards/${cardId}`, cardForm, {
      headers: getAuthHeaders(),
    });
    return response.data;
  } catch (error) {
    console.error('更新卡片失败:', error);
    throw error;
  }
}

// 删除卡片
export async function deleteCard(cardId) {
  try {
    await axios.delete(`${baseUrl}/api/cards/${cardId}`, {
      headers: getAuthHeaders(),
    });
  } catch (error) {
    console.error('删除卡片失败:', error);
    throw error;
  }
}

// 获取所有题目
export function fetchQuestions() {
  return axios.get(`${baseUrl}/api/questions`, {
    headers: getAuthHeaders()
  });
}

// 添加新题目
export function addNewQuestion(newQuestion) {
  return axios.post(`${baseUrl}/api/questions`, newQuestion, {
    headers: getAuthHeaders()
  });
}

// 更新题目
export function updateQuestion(questionId, updatedQuestion) {
  return axios.put(`${baseUrl}/api/questions/${questionId}`, updatedQuestion, {
    headers: getAuthHeaders()
  });
}

// 删除题目
export function deleteQuestion(questionId) {
  return axios.delete(`${baseUrl}/api/questions/${questionId}`, {
    headers: getAuthHeaders()
  });
}